package studio.raptor.extractor.segment.listeners;

import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import studio.raptor.cmdb.ConfigFile;
import studio.raptor.cmdb.ConfigService;
import studio.raptor.cmdb.core.enums.ConfigFileFormat;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

/**
 * Created by liuyong8 on 2017/7/13. load extractor.properties
 */
public class ExtractorApplicationListener
    implements
      ApplicationListener<ApplicationEnvironmentPreparedEvent> {

  private static final Logger log = LoggerFactory.getLogger(ExtractorApplicationListener.class);

  @Override
  public void onApplicationEvent(
      ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
    log.info("开始 从配置中心获取抽取程序配置!");
    ConfigFile extractorConfig = ConfigService
            .getConfigFile("extractor", ConfigFileFormat.Properties);
    ConfigFile applicationConfig = ConfigService.getConfigFile("application", ConfigFileFormat.Properties);

    Properties extractorProperties = parsePropertiesString(extractorConfig.getContent(),
            "extractor.properties");
    Properties applicationProperties = parsePropertiesString(applicationConfig.getContent(),
            "application.properties");


    log.info("extractor config:{}",extractorProperties.toString());
    log.info("application config:{}", applicationProperties.toString());

    ConfigurableEnvironment envi = applicationEnvironmentPreparedEvent.getEnvironment();
    MutablePropertySources mps = envi.getPropertySources();

    if (mps != null) {
      mps.addFirst(new PropertiesPropertySource("extractor", extractorProperties));
      mps.addFirst(new PropertiesPropertySource("application", applicationProperties));
    }
    log.info("结束 从配置中心获取抽取程序配置!");
  }


  private Properties parsePropertiesString(String config, String file) {
    Preconditions.checkArgument(config != null, "the config" + file + "is empty or not exists");
    final Properties p = new Properties();
    try {
      p.load(new StringReader(config));
    } catch (IOException e) {
      log.error("parsePropertiesString error:", e);
    }
    return p;
  }
}


